import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

@WebServlet("/index")
public class GuessNum extends HttpServlet {
    //实例模板引擎
    private TemplateEngine engine = new TemplateEngine();
    private int num;
    private int count;

    @Override
    public void init() throws ServletException {
        //构造模板解析器
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(this.getServletContext());
        resolver.setPrefix("/WEB-INF/template/");
        resolver.setSuffix(".html");
        resolver.setCharacterEncoding("utf-8");
        engine.setTemplateResolver(resolver);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        Random random = new Random();
        num = random.nextInt(100)+1;
        count = 0;
        WebContext webContext = new WebContext(req,resp,this.getServletContext());
        webContext.setVariable("newName",true);
        engine.process("hello",webContext,resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        String str = req.getParameter("num");
        int newNum = Integer.parseInt(str);
        String result;
        if (newNum == num){
            result = "猜对了";
        }else if(newNum > num){
            result = "猜大了";
        }else {
            result = "猜小了";
        }
        WebContext webContext = new WebContext(req,resp,this.getServletContext());
        webContext.setVariable("newName",false);
        webContext.setVariable("result",result);
        count++;
        webContext.setVariable("count",count);
        engine.process("hello",webContext,resp.getWriter());
    }
}
